<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="零部件号" prop="code" class="item">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入零部件号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="零件名称" prop="name" class="item">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入零部件名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="材料品号" prop="pinhao" class="item">
        <el-input
          v-model="queryParams.pinhao"
          placeholder="请输入材料品号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="规格型号" prop="model" class="item">
        <el-input
          v-model="queryParams.model"
          placeholder="请输入规格型号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="现存状态" prop="partState" class="item"> 
        <el-select v-model="queryParams.partState" placeholder="请选择现存状态" clearable size="small">
          <el-option
            v-for="dict in partStateOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="使用状态" prop="partUseState" class="item">
        <el-select v-model="queryParams.partUseState" placeholder="请选择使用状态" clearable size="small">
          <el-option
            v-for="dict in partUseStateOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="存放地点" prop="address" class="item">
        <el-input
          v-model="queryParams.address"
          placeholder="请输入存放地点"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物资由来" prop="derive" class="item">
        <el-input
          v-model="queryParams.derive"
          placeholder="请输入物资由来"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
       <el-form-item label="入库时间" class="item">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['trialproduce:part:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['trialproduce:part:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['trialproduce:part:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" icon="el-icon-upload2" size="mini" @click="handleImport" v-hasPermi="['trialproduce:part:import']">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['trialproduce:part:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handlePartState"
          v-hasPermi="['trialproduce:part:carstate']"
        >零件状态</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="partList" @selection-change="handleSelectionChange" border style="width: 100%" height="600">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="零件ID" align="center" prop="partId" width="55" v-if="false"/>
      <el-table-column label="零部件号" align="center" prop="code" fixed/>
      <el-table-column label="零件名称" align="center" prop="name" />
      <el-table-column label="现存状态" align="center" prop="partState" :formatter="partStateFormat" />
      <el-table-column label="使用状态" align="center" prop="partUseState" :formatter="partUseStateFormat" />
      <el-table-column label="材料品号" align="center" prop="pinhao" />
      <el-table-column label="规格型号" align="center" prop="model" />
      <el-table-column label="计量单位" align="center" prop="unitName" />
      <el-table-column label="单价" align="center" prop="price" />
      <el-table-column label="账面数量" align="center" prop="partNum" />
      <el-table-column label="存放地点" align="center" prop="address" />
      <el-table-column label="物资由来" align="center" prop="derive" />
      <el-table-column label="入库时间" align="center" prop="productionTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.productionTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="使用履历" align="center" prop="record" width="300" :show-overflow-tooltip="true"/>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="80" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['trialproduce:part:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['trialproduce:part:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改零件对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="零部件号" prop="code">
              <el-input v-model="form.code" placeholder="请输入零部件号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="零件名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入零部件名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="材料品号" prop="pinhao">
              <el-input v-model="form.pinhao" placeholder="请输入材料品号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格型号" prop="model">
              <el-input v-model="form.model" placeholder="请输入规格型号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计量单位" prop="unitName">
              <el-input v-model="form.unitName" placeholder="请输入计量单位" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单价" prop="price">
              <el-input v-model="form.price" placeholder="请输入单价" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="账面数量" prop="partNum">
              <el-input v-model="form.partNum" placeholder="请输入账面数量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="存放地点" prop="address">
              <el-input v-model="form.address" placeholder="请输入存放地点" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物资由来" prop="derive">
              <el-input v-model="form.derive" placeholder="请输入物资由来" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库时间" prop="productionTime">
              <el-date-picker clearable size="small" style="width:100%"
                v-model="form.productionTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择入库时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="现存状态">
              <el-radio-group v-model="form.partState">
                <el-radio
                  v-for="dict in partStateOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="使用状态">
              <el-radio-group v-model="form.partUseState">
                <el-radio
                  v-for="dict in partUseStateOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="使用履历" prop="record">
              <el-input v-model="form.record" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body :close-on-click-modal="false">
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的数据
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改零件状态 -->
    <el-dialog :title="partstate.title" :visible.sync="partstate.open" width="550px" append-to-body :close-on-click-modal="false">
      <el-form ref="partstate.form" :model="partstate.form" :rules="partstate.rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="关联ID" prop="partIds"  v-if="false">
              <el-input v-model="repair.form.partIds" placeholder="请输入关联ID" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="零件状态">
              <el-radio-group v-model="partstate.form.partState">
                <el-radio
                  v-for="dict in partStateOptions"
                  :key="dict.dictValue"
                  :label="parseInt(dict.dictValue)"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="使用状态">
              <el-radio-group v-model="partstate.form.partUseState">
                <el-radio
                  v-for="dict in partUseStateOptions"
                  :key="dict.dictValue"
                  :label="parseInt(dict.dictValue)"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPartForm">确 定</el-button>
        <el-button @click="cancelPartState">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPart, getPart, delPart, addPart, updatePart, exportPart, importTemplate, changeState  } from "@/api/trialproduce/part";
import { getToken } from "@/utils/auth";
export default {
  name: "Part",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 日期范围
      dateRange: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 零件表格数据
      partList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 现存状态字典
      partStateOptions: [],
      // 使用状态字典
      partUseStateOptions: [],
      //导入参数
      upload: {
        // 是否显示弹出层（导入）
        open: false,
        // 弹出层标题（导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/trialproduce/part/importData",
      },
      //修改状态信息
      partstate: {
        // 是否显示弹出层（）
        open: false,
        // 弹出层标题（）
        title: "",
        //表单
        form: {

        },
        // 表单校验
        rules: {
        }
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        name: null,
        pinhao: null,
        model: null,
        partState: null,
        partUseState: null,
        address: null,
        derive: null,
        productionTime: null,
       
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("part_state").then(response => {
      this.partStateOptions = response.data;
    });
    this.getDicts("part_use_state").then(response => {
      this.partUseStateOptions = response.data;
    });
  },
  methods: {
    /** 查询零件列表 */
    getList() {
      this.loading = true;
      listPart(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.partList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 现存状态字典翻译
    partStateFormat(row, column) {
      return this.selectDictLabel(this.partStateOptions, row.partState);
    },
    // 使用状态字典翻译
    partUseStateFormat(row, column) {
      return this.selectDictLabel(this.partUseStateOptions, row.partUseState);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        partId: null,
        code: null,
        name: null,
        pinhao: null,
        model: null,
        unitName: null,
        price: null,
        partNum: null,
        partState: "0",
        partUseState: "0",
        address: null,
        derive: null,
        productionTime: null,
        record: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      //工时范围
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.partId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加零件";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const partId = row.partId || this.ids
      getPart(partId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改零件";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.partId != null) {
            updatePart(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addPart(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const partIds = row.partId || this.ids;
      this.$confirm('是否确认删除零件编号为"' + partIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delPart(partIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有零件数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportPart(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "零部件导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then((response) => {
        this.download(response.msg);
      });
    },
     // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    //修改零部件状态
    handlePartState(){
      this.partstate.open = true;
      this.partstate.title = "零部件状态变更";
    },
    // 状态表单重置
    partstateReset(){
      this.partstate.form = {
        partIds : "",
        partState : null,
        partUseState : null
      };
      this.partstate.isShow = false;
      this.resetForm("partstate.form");
    },
    submitPartForm(row){
      const partIds = row.partId || this.ids;
      this.partstate.form.partIds = partIds;
      this.$refs["partstate.form"].validate(valid => {
        if (valid) {
            changeState(this.partstate.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("状态更改成功");
                this.partstate.open = false;
                this.partstateReset();
                this.getList();
              }
            });
        }
      });
    },
      // 取消按钮
    cancelPartState() {
      this.partstate.open = false;
      this.partstateReset();
    },
  }
};
</script>
